package com.czxy.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

// 声明该类是一个 配置类
@Configuration
// 扫描各个包
@ComponentScan({"com.czxy"})
// 读取db.properties配置文件中的数据库信息
@PropertySource("classpath:db.properties")
// 支持事务操作
@EnableTransactionManagement
public class SpringConfig {

    // 4.2.4版本 固定配置
    @Bean
    public static PropertySourcesPlaceholderConfigurer create(){
        return  new PropertySourcesPlaceholderConfigurer();
    }

    //读取数据库相关配置
    @Value("${jdbc.driver}")
    private String driverClass;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    //数据源使用德鲁伊连接池
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driverClass);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    // 开启事务管理器
    @Bean
    @Resource
    public DataSourceTransactionManager txManager(DataSource dataSource){
        return  new DataSourceTransactionManager(dataSource);
    }


}
